package com.cu.employmentmanagementsystem.util;

import cn.dev33.satoken.stp.StpUtil;
import com.cu.employmentmanagementsystem.config.RedisCacheConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;


@Component
public class SaTokenPlugin
{
    private static RedisTemplate<String, String> userTokenRedisTemplate;

    public static void unsealUer(String account)
    {
        StpUtil.untieDisable(account);
    }

    @Autowired
    @Resource(name = RedisCacheConfig.REDIS_TEMPLATE_USER_TOKEN)
    public void setDefaultRedisTemplate(RedisTemplate<String, String> userTokenRedisTemplate)
    {
        SaTokenPlugin.userTokenRedisTemplate = userTokenRedisTemplate;
    }

    /**
     * 获取所有有效token集合
     *
     * @return
     */
    public static Map<String, String> getAllUserTokenMap()
    {
        Set<String> keys = userTokenRedisTemplate.keys("*");
        assert keys != null;

        HashMap<String, String> userTokenMap = new HashMap<>();
        for (String key : keys)
        {
            if (key.contains("session"))
            {
                String account = key.substring(key.lastIndexOf(":") + 1);
                String token = StpUtil.getTokenValueByLoginId(account);
                userTokenMap.put(account, token);
            }
        }
        return userTokenMap;
    }

    public static List<String> getAllUserAccountList()
    {
        Set<String> keys = userTokenRedisTemplate.keys("*");
        assert keys != null;

        ArrayList<String> accountList = new ArrayList<>();
        for (String key : keys)
        {
            if (key.contains("session"))
            {
                String account = key.substring(key.lastIndexOf(":") + 1);
                accountList.add(account);
            }
        }
        return accountList;
    }

    public static void closeSystem()
    {
        List<String> allUserAccountList = getAllUserAccountList();
        for (String account : allUserAccountList)
        {
            if (!isAdmin(account))
            {
                StpUtil.kickout(account);
            }
        }
    }

    public static boolean isAdmin(String account)
    {
        List<String> roleList = StpUtil.getRoleList(account);
        return roleList.contains("admin");
    }

    public static void banUser(String account)
    {
        //先注销
        StpUtil.logout(account);
        //再封禁
        StpUtil.disable(account, -1);
    }
}
